package message;

import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.util.function.Consumer;

import message.reflect.HandlerMapper;
import message.util.Step;

public class ObjectMessageBuilderSupplier implements MessageBuilderSupplier {

	private HandlerMapper mapper;
	public ObjectMessageBuilderSupplier(HandlerMapper mapper) {
		this.mapper = mapper;
	}
	
	@Override
	public MessageBuilder get(Consumer<? super Object> callback) {
		return new AbstractMessageBuilder(callback) {
			private long code;
			private MessageBuilder builder;
			private Step step = new Step();
			@Override
			public boolean read(ByteBuffer byteBuffer) {
				if(step.is(0)) {
					try {
						code = byteBuffer.getLong();
						if(code == 0) return true;
					} catch (BufferUnderflowException e) {
						return false;
					}
					try {
						builder = mapper.getBuilderSupplier(Class.forName(mapper.getType(code))).get((x)->{
							this.build = x;
						});
					} catch (ClassNotFoundException e) {
						e.printStackTrace();
					}
					step.done();
				}
				if(step.is(1)) {
					if(!(builder.read(byteBuffer))) return false;
					step.done();
				}
				return super.read(byteBuffer);
			}
		};
	}


}
